/* eslint-disable no-restricted-syntax */
import { Module } from 'vuex'
import { RouteRecordRaw } from 'vue-router'
import router, { constantRoutes, asyncRoutes, pageRoutes } from '@/router'
import permissionStateTypes from './types'
import RootStateTypes from '../../types'
// import Service from './api'
import { computed, onMounted } from 'vue'

const roles = localStorage.getItem('role') || ''

// create a new Store Modules.
const permissionModule: Module<permissionStateTypes, RootStateTypes> = {
  namespaced: true,
  state: {
    roles, // 用户包含的角色,
    permissions: [], // 用户指定局部操作权限
    accessRoutes: constantRoutes, // 可访问路由集合
    routes: constantRoutes, // 所有路由集合
    authedRoutes: [],
    routeFlag: false   // 标记是否缓存路由
  },
  mutations: {
    setRoles: (state: permissionStateTypes, { roleName }) => {
      state.roles = roleName
    },
    setAccessRoutes: (state: permissionStateTypes, routes) => {
      // state.accessRoutes = constantRoutes.concat(routes)
      state.accessRoutes = routes
      sessionStorage.setItem("accessRoutes", JSON.stringify(routes))
      sessionStorage.setItem("routeFlag", "true")
      console.log('可访问路由', state.accessRoutes)
    },
    setRoutes: (state: permissionStateTypes, routes) => {
      state.routes = constantRoutes.concat(routes)
    },
    setAuthedRoutes: (state: permissionStateTypes, authedRoutes: string[]) => {
      state.authedRoutes = authedRoutes
      localStorage.setItem('authedRoutes', JSON.stringify(authedRoutes))
    },
    setPermissions: (state: permissionStateTypes, permissions: string[]) => {
      state.permissions = permissions
    },
    setRouteFlag: (state: permissionStateTypes, routeFlag: boolean) => {
      state.routeFlag = routeFlag
    },
  },
  actions: {
    // 异步接口请求，动态添加路由
    async getPermissonRoutes({ commit }, payload: any) {
      let routes: RouteRecordRaw[] = []
      // 系统授权资源
      const resourceList = payload.resourceList;
      // 根据角色获取授权菜单
      const role = { roles: payload.roleName }
      routes = await pageRoutes(role, resourceList)

      // 动态添加路由  vue-router4.x 暂时没有addRoutes
      router.isReady().then(() => {
        routes.forEach((route: RouteRecordRaw) => {
          const routeName: any = route.name
          if (!router.hasRoute(routeName)) {
            router.addRoute(route)
          }
        })
        // router.options.routes = constantRoutes.concat(asyncRoutes)
        console.log('路由', router.getRoutes())
        commit('setAccessRoutes', routes)
      })
    },
    // getPermissions({ commit }) {
    //   // 后端根据角色名称，查询授权菜单
    //   Service.postPermissions({}).then((res) => {
    //     const { permissions } = res.data
    //     commit('setPermissions', permissions)
    //   })
    // },

    getRoutes({ commit }) {
      // 动态添加路由  vue-router4.x 暂时没有addRoutes
      if (localStorage.getItem('authedRoutes')) {

        const authedRoutes = JSON.parse(localStorage.getItem('authedRoutes') as string)
        const accessedRoutes: RouteRecordRaw[] = []
        for (const path of authedRoutes) {
          for (const item of asyncRoutes) {
            if (item.path === path) {
              accessedRoutes.push(item)
            }
          }
        }
        accessedRoutes.forEach((route: RouteRecordRaw) => {
          const routeName: any = route.name
          if (!router.hasRoute(routeName)) {
            router.addRoute(route)
          }
        })
      }

      commit('setRoutes', asyncRoutes)
    },
    // 保存用户角色
    getPermissonRoles({ commit }, payload: any) {
      // api request
      if (payload.userName === 'super') {
        localStorage.setItem('role', 'super')
      } else {
        const roleList = payload.roleList;
        let roles = ''
        if (roleList) {
          for (const role in roleList) {
            roles += ',' + role[roleCode];
          }
          roles = roles.substring(1)
        }
        localStorage.setItem('role', roles)
      }
      commit('setRoles', payload)
    }
  },
  getters: {
    getAccessRoutes(state: permissionStateTypes) {
      return state.routes
    },
    authedRoutes(state: permissionStateTypes) {
      return state.authedRoutes
    },
    getRoles(state: permissionStateTypes) {
      return state.roles
    },
    getPermission(state: permissionStateTypes) {
      return state.permissions
    },
    getRouteFlag(state: permissionStateTypes) {
      return state.routeFlag
    },
  }
}
export default permissionModule
